package com.qyhl.webtv.module_news.luckydraw.nineluck;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.just.library.AgentWeb;
import com.just.library.WebDefaultSettingsManager;
import com.just.library.WebSettings;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DESedeUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.LuckDrawUrlBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.weavey.loading.lib.LoadingLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import butterknife.BindView;

/**
 * 九宫格抽奖
 */
@Route(path = ARouterPathConstant.NINE_LUCK_DRAW)
public class NinePhotoLuckDrawActivity extends BaseActivity {
    @BindView(R2.id.adv_toolbar)
    Toolbar advToolbar;
    @BindView(R2.id.adv_web_layout)
    LinearLayout advWebLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.title)
    TextView title;

    private AgentWeb mAgentWeb;
    private int actId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_nine_luck_draw;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        actId = getIntent().getIntExtra("id", 0);
        setSupportActionBar(advToolbar);
        getData();
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            getData();
        });
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            if (mAgentWeb == null) {
                finish();
            } else if (!mAgentWeb.back()) {
                finish();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void getData() {
        String userName = CommonUtils.getInstance().getUserName();
        Map<String, String> map = DESedeUtil.encodeMapUrl(CommonUtils.getInstance().getIntegralUrl());
        JSONObject object = new JSONObject();
        try {
            object.put("siteId", CommonUtils.getInstance().getSite());
            object.put("version", 1);
            object.put("name", "getLotteryUrl");
            object.put("username", userName);
            object.put("actId", actId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        EasyHttp.post(map.get(DESedeUtil.URL))
                .upBytes(DESedeUtil.encryptMode(map.get(DESedeUtil.CODEKEY), object.toString()))
                .isDecrypt(true)
                .decryptKet(map.get(DESedeUtil.CODEKEY))
                .execute(new SimpleCallBack<LuckDrawUrlBean>() {
                    @Override
                    public void onError(ApiException e) {
                        loadMask.setReloadButtonText("点击重试~");
                        loadMask.setStatus(LoadingLayout.Error);
                    }

                    @Override
                    public void onSuccess(LuckDrawUrlBean luckDrawUrlBean) {
                        if (luckDrawUrlBean.getUrl() != null) {
                            loadMask.setStatus(LoadingLayout.Success);
                            loadMask.setReloadButtonText("点击重试~");
                            title.setText(StringUtils.isEmpty(luckDrawUrlBean.getTitle()) ? "" : luckDrawUrlBean.getTitle());
                            mAgentWeb = AgentWeb.with(NinePhotoLuckDrawActivity.this)//传入Activity or Fragment
                                    .setAgentWebParent(advWebLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                                    .useDefaultIndicator()// 使用默认进度条
                                    .defaultProgressBarColor() // 使用默认进度条颜色
                                    .setWebSettings(new CustomSettings())
                                    .createAgentWeb()
                                    .ready()
                                    .go(luckDrawUrlBean.getUrl());
                        } else {
                            loadMask.setReloadButtonText("点击重试~");
                            loadMask.setStatus(LoadingLayout.Error);
                        }
                    }
                });

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mAgentWeb == null) {
                    finish();
                } else if (!mAgentWeb.back()) {
                    finish();
                }
                return true;
            default:
                break;
        }


        return super.onKeyDown(keyCode, event);
    }

    class CustomSettings extends WebDefaultSettingsManager {
        CustomSettings() {
            super();
        }


        @Override
        public WebSettings toSetting(WebView webView) {
            super.toSetting(webView);
            String path = Environment.getExternalStorageDirectory().getPath() + "/baidudata";//百度地图调用需要
            File tmpFile = new File(path);
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            getWebSettings().setGeolocationDatabasePath(path);
            getWebSettings().setDomStorageEnabled(true);
            getWebSettings().setBlockNetworkImage(false);//是否阻塞加载网络图片  协议http or https
            getWebSettings().setAllowFileAccess(false); //允许加载本地文件html  file协议, 这可能会造成不安全 , 建议重写关闭
            getWebSettings().setAllowFileAccessFromFileURLs(false); //通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
            getWebSettings().setAllowUniversalAccessFromFileURLs(false);//允许通过 file url 加载的 Javascript 可以访问其他的源，包括其他的文件和 http，https 等其他的源
            getWebSettings().setUseWideViewPort(true);
            getWebSettings().setSupportZoom(true);
            getWebSettings().setBuiltInZoomControls(true);
            return this;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.LOTTERY);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.LOTTERY);
    }
}
